/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package lyra;

import java.awt.Component;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import lyra.pojos.*;

/**
 *
 * @author Koustas, Marmaridis, Mariolou
 */
public class FArtistAlbum extends javax.swing.JInternalFrame {

    Album album;
    Album OriginalAlbum;
    private List<Object[]> curSongs;
    boolean bChanges = false;
    boolean bFormLoaded = false;
    boolean bFormClosing = false;
    
    /**
     * Creates new form frmArtist
     */
    private FListArtistAlbum  parentForm;

   SimpleDateFormat sDF = new SimpleDateFormat("dd/MM/yyyy");

   public class AlbumTypeListCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(
            JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value instanceof Albumtype) {
            Albumtype c = (Albumtype) value;
            setText(c.getName());
        }
        return this;
    }

}

public class MusicProductionCompanyListCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(
            JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value instanceof Musicproductioncompany) {
            Musicproductioncompany c = (Musicproductioncompany) value;
            setText(c.getName());
        }
        return this;
    }

}

public class ArtistListCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(
            JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value instanceof Artist) {
            Artist c = (Artist) value;
            setText(c.getFirstname() + ' ' + c.getLastname());
        }
        return this;
    }
}

public class SongListCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(
            JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value instanceof Song) {
            Song c = (Song) value;
            setText(c.getTitle());
        }
        return this;
    }
}

    private class SongTableModel extends AbstractTableModel 
    {
   
        private List<Object[]> vwsongs;
           
        private final String[] columnNames = new String[] {"SongID", "Τίτλος", "Διάρκεια", "Αριθμός Σειράς"};
        private final Class[] columnClass = new Class[] {Long.class, String.class, Integer.class, Integer.class};
 
        public SongTableModel(List<Object[]> vwsongs)
        {
           this.vwsongs = vwsongs;
        }

        public void removeRow(int row) {
            vwsongs.remove(row);
        }

       public void addRow(Object[] newRow) {
            vwsongs.add(newRow);
        }

        @Override
        public String getColumnName(int column)
        {
            return columnNames[column];
        }
 
        @Override
        public Class<?> getColumnClass(int columnIndex)
        {
            return columnClass[columnIndex];
        }

        @Override
        public int getColumnCount()
        {
            return columnNames.length;
        }

        @Override
        public int getRowCount()
        {
            return vwsongs.size();
        }
        
        @Override
        public boolean isCellEditable(int row, int col) {
            return true;
        }

        @Override
        public void setValueAt(Object obj, int rowIndex, int columnIndex) {
            try {
                Object[] row = (Object[]) this.vwsongs.get(rowIndex);
                if (bFormLoaded) setChanges(true);
                row[columnIndex] = obj;
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            }
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex)
        {
            try {
                Object[] row = (Object[]) this.vwsongs.get(rowIndex);
                return row[columnIndex];
            } catch (Exception ex) {
                    ex.printStackTrace(System.out);
                    return null;
            }

        }
   }

    public FArtistAlbum(FListArtistAlbum parent) {

        initComponents();
        
        this.parentForm = parent;
        
        this.setTitle("Εισαγωγή στοιχείων άλμπουμ καλλιτέχνη");
        Insertion();
        dtDateRelease.setFormats("dd/MM/yyyy");
        setLockCtrls(false);
        
        cmbAlbumType.setRenderer(new AlbumTypeListCellRenderer());
        cmbArtist.setRenderer(new ArtistListCellRenderer());
        cmbMusicProductionCompany.setRenderer(new MusicProductionCompanyListCellRenderer());
        
        fillPlayListSongs(-1);
        bFormLoaded = true;
        LYRA.setFrameIcon(this,"AudioCD20.png");
        parentForm.EnableDisableForm(false);
    }
    
    final void fillPlayListSongs(long albumID) {
       
        curSongs = new ArrayList();
        
        if (albumID == -1) {
            Query qPlayListSongs = LYRA.e.createNativeQuery("SELECT sng.SongID, sng.Title, sng.Duration, sng.TrackNR FROM ADMIN1.Song sng WHERE 1=2");
            curSongs = (List<Object[]>)qPlayListSongs.getResultList();
        } else {
            Query qPlayListSongs = LYRA.e.createNativeQuery("SELECT sng.SongID, sng.Title, sng.Duration, sng.TrackNR FROM ADMIN1.Song sng WHERE sng.AlbumID = " + albumID);
            curSongs =  (List<Object[]>)qPlayListSongs.getResultList();
        }
        
        SongTableModel model = new SongTableModel(curSongs);
        
        tblSongs.setModel(model);
        this.tblSongs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        for (int intCol=0;intCol<=0;intCol++) {
            if (tblSongs.getColumnModel().getColumnCount() > intCol) {
                tblSongs.getColumnModel().getColumn(intCol).setMinWidth(0);
                tblSongs.getColumnModel().getColumn(intCol).setMaxWidth(0);
            }
        }
        this.tblSongs.setCellSelectionEnabled(false); 
        this.tblSongs.setRowSelectionAllowed(true); 

    }

    public FArtistAlbum(FListArtistAlbum parent, Album alb ) {

        OriginalAlbum = alb;
        initComponents();
        album = OriginalAlbum;
        this.parentForm = parent;
        
        this.setTitle("Μεταβολή στοιχείων άλμπουμ καλλιτέχνη");
        dtDateRelease.setFormats("dd/MM/yyyy");
        setLockCtrls(false);
        
        cmbAlbumType.setRenderer(new AlbumTypeListCellRenderer());
        cmbArtist.setRenderer(new ArtistListCellRenderer());
        cmbMusicProductionCompany.setRenderer(new MusicProductionCompanyListCellRenderer());
        fillPlayListSongs(alb.getAlbumid());
        
        bFormLoaded = true;
        LYRA.setFrameIcon(this,"AudioCD20.png");
        parentForm.EnableDisableForm(false);
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        LYRAPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("LYRAPU").createEntityManager();
        lyra.pojos.Album album = OriginalAlbum;
        songQuery = java.beans.Beans.isDesignTime() ? null : LYRAPUEntityManager.createQuery("SELECT s FROM Song s");
        songList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : songQuery.getResultList();
        musicproductioncompanyQuery = java.beans.Beans.isDesignTime() ? null : LYRAPUEntityManager.createQuery("SELECT m FROM Musicproductioncompany m");
        musicproductioncompanyList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : musicproductioncompanyQuery.getResultList();
        albumtypeQuery = java.beans.Beans.isDesignTime() ? null : LYRAPUEntityManager.createQuery("SELECT a FROM Albumtype a");
        albumtypeList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(albumtypeQuery.getResultList());
        artistQuery = java.beans.Beans.isDesignTime() ? null : LYRAPUEntityManager.createQuery("SELECT a FROM Artist a");
        artistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : artistQuery.getResultList();
        tbarManage = new javax.swing.JToolBar();
        tbbModify = new javax.swing.JButton();
        tbbInsert = new javax.swing.JButton();
        tbbDelete = new javax.swing.JButton();
        tbbExit = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtTitle = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        dtDateRelease = new org.jdesktop.swingx.JXDatePicker();
        cmbAlbumType = new javax.swing.JComboBox();
        txtDiskNumber = new javax.swing.JTextField();
        cmbMusicProductionCompany = new javax.swing.JComboBox();
        cmbArtist = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        btnAdd = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblSongs = new javax.swing.JTable();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Άλμπουμ (Καλλιτέχνη)");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        tbarManage.setFloatable(false);
        tbarManage.setRollover(true);

        tbbModify.setText("Αποθήκευση");
        tbbModify.setFocusable(false);
        tbbModify.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbbModify.setPreferredSize(new java.awt.Dimension(50, 50));
        tbbModify.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbbModify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tbbModifyActionPerformed(evt);
            }
        });
        tbarManage.add(tbbModify);

        tbbInsert.setText("Εισαγωγή");
        tbbInsert.setFocusable(false);
        tbbInsert.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbbInsert.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbbInsert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tbbInsertActionPerformed(evt);
            }
        });
        tbarManage.add(tbbInsert);

        tbbDelete.setText("Διαγραφή");
        tbbDelete.setFocusable(false);
        tbbDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbbDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbbDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tbbDeleteActionPerformed(evt);
            }
        });
        tbarManage.add(tbbDelete);

        tbbExit.setText("Έξοδος");
        tbbExit.setFocusable(false);
        tbbExit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbbExit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbbExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tbbExitActionPerformed(evt);
            }
        });
        tbarManage.add(tbbExit);

        jPanel1.setBackground(new java.awt.Color(204, 255, 255));

        jLabel1.setText("Τίτλος:");

        jLabel3.setText("Αριθμός Άλμπουμ:");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${title}"), txtTitle, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtTitle.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTitleKeyTyped(evt);
            }
        });

        jLabel4.setText("Εταιρεία Παραγωγής:");

        jLabel2.setText("Τύπος Άλμπουμ:");

        jLabel6.setText("Καλλιτέχνης:");

        jLabel5.setText("Ημερομηνία κυκλοφορίας:");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${releasedate}"), dtDateRelease, org.jdesktop.beansbinding.BeanProperty.create("date"));
        bindingGroup.addBinding(binding);

        dtDateRelease.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dtDateReleaseActionPerformed(evt);
            }
        });

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${resultList}");
        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, albumtypeQuery, eLProperty, cmbAlbumType);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${albumtypeid}"), cmbAlbumType, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cmbAlbumType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbAlbumTypeActionPerformed(evt);
            }
        });

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${disknumber}"), txtDiskNumber, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtDiskNumber.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDiskNumberKeyTyped(evt);
            }
        });

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${resultList}");
        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, musicproductioncompanyQuery, eLProperty, cmbMusicProductionCompany);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${musicproductioncompanyid}"), cmbMusicProductionCompany, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cmbMusicProductionCompany.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbMusicProductionCompanyActionPerformed(evt);
            }
        });

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${resultList}");
        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistQuery, eLProperty, cmbArtist);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${artistid}"), cmbArtist, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cmbArtist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbArtistActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(dtDateRelease, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(229, 229, 229))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cmbAlbumType, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cmbMusicProductionCompany, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtDiskNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cmbArtist, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbAlbumType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDiskNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cmbMusicProductionCompany, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(cmbArtist, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dtDateRelease, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(0, 17, Short.MAX_VALUE))
        );

        jLabel7.setBackground(new java.awt.Color(51, 255, 51));
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel7.setText("Λίστα Τραγουδιών");

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/add.gif"))); // NOI18N
        btnAdd.setText("Εισαγωγή Τραγουδιού");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delete.png"))); // NOI18N
        btnRemove.setText("Διαγραφή Τραγουδιού");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${songCollection}");
        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, eLProperty, tblSongs);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songid}"));
        columnBinding.setColumnName("Songid");
        columnBinding.setColumnClass(Long.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tracknr}"));
        columnBinding.setColumnName("Tracknr");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${title}"));
        columnBinding.setColumnName("Title");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${duration}"));
        columnBinding.setColumnName("Duration");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumid}"));
        columnBinding.setColumnName("Albumid");
        columnBinding.setColumnClass(lyra.pojos.Album.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane3.setViewportView(tblSongs);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, Short.MAX_VALUE))
                            .addComponent(tbarManage, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 18, Short.MAX_VALUE))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnAdd)
                .addGap(41, 41, 41)
                .addComponent(btnRemove)
                .addGap(57, 57, 57))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(16, Short.MAX_VALUE)
                .addComponent(tbarManage, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnRemove))
                .addGap(7, 7, 7))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void StartEdit()
    {
        setLockCtrls(false);
        //setChanges(false);
    }
            
    private void FinisEdit()
    {
        setLockCtrls(true);

        tbbModify.setEnabled(true);
        //tbbModify.setIcon("imgUpdate.png");
    }
    
    private void setLockCtrls(boolean lock)
    {
        if (lock) 
        {
            tbbModify.setText("Αποθήκευση");
            tbbExit.setText("Έξοδος");
        }
        else
        {
            tbbModify.setText("Αποθήκευση");
            tbbExit.setText("Ακύρωση");
        }
        
        tbbModify.setEnabled(bChanges);
        tbbInsert.setEnabled(lock);
        tbbDelete.setEnabled(lock);

        txtDiskNumber.setEditable(!lock);
        txtTitle.setEditable(!lock);
        txtDiskNumber.setEditable(!lock);
        cmbAlbumType.setEnabled(!lock);
        cmbArtist.setEnabled(!lock);
        cmbMusicProductionCompany.setEnabled(!lock);
        dtDateRelease.setEditable(!lock);
        
    }
    
    private boolean isDataOK()
    {
        //Έλεγχος ύπαρξης Επωνύμου & Ονόματος
        if ( (txtTitle.getText().trim()).length() == 0 )
        {
            LYRA.MsgBox("Πρέπει να δοθεί τίτλος υποχρεωτικά", "ΠΡΟΣΟΧΗ");
            txtTitle.setFocusable(true);
            return false;
        }
        if ( (txtDiskNumber.getText().trim()).length() == 0 )
        {
            LYRA.MsgBox("Πρέπει να δοθεί αριθμός άλμπουμ υποχρεωτικά", "ΠΡΟΣΟΧΗ");
            txtDiskNumber.setFocusable(true);
            return false;
        }
        try {
            int iDiskNumber = Integer.parseInt(txtDiskNumber.getText().trim());
            if (iDiskNumber <= 0) {
                LYRA.MsgBox("Πρέπει να δοθεί αριθμός άλμπουμ υποχρεωτικά (>=1)", "ΠΡΟΣΟΧΗ");
                txtDiskNumber.setFocusable(true);
                return false;
            }
            txtDiskNumber.setText(Integer.toString(iDiskNumber));
        } catch (Exception ex) {
            LYRA.MsgBox("Πρέπει να δοθεί αριθμός άλμπουμ υποχρεωτικά (>=1)", "ΠΡΟΣΟΧΗ");
            txtDiskNumber.setFocusable(true);
            return false;
        }
        //έλεγχος combo
        if (cmbAlbumType.getSelectedItem() == null) 
        {
            LYRA.MsgBox("Δεν έχει επιλεγεί ο τύπος του άλμπουμ", "ΠΡΟΣΟΧΗ");
            cmbAlbumType.setFocusable(true);
            return false;
        }
        
        if ((curSongs == null) || (curSongs.size() < 1)) {
            LYRA.MsgBox("Πρέπει να καταχωρηθεί τουλάχιστον ένα τραγούδι", "ΠΡΟΣΟΧΗ");
            return false;
        }
     
        for (int iRow=0;iRow<curSongs.size();iRow++) {
            Object[] row_1 = (Object[]) curSongs.get(iRow);
            for (int yRow=iRow+1;yRow<curSongs.size();yRow++) {
                Object[] row_2 = (Object[]) curSongs.get(yRow);
                
                if (((String)row_1[1]).equals((String)row_2[1])) {
                    LYRA.MsgBox("Υπάρχουν δύο τραγούδια με το ίδιο όνομα!", "ΠΡΟΣΟΧΗ");
                    return false;
               }
            } 
        }
            
        
        //αν φτάσει ως εδώ τα δεδομένα είναι ΟΚ
        return true;
    }

    private void txtTitleKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTitleKeyTyped
        if (bFormLoaded) setChanges(true);
    }//GEN-LAST:event_txtTitleKeyTyped
            
    private void tbbModifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbbModifyActionPerformed
        UpdateArtistAlbum();
    }//GEN-LAST:event_tbbModifyActionPerformed

    private void tbbInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbbInsertActionPerformed
        Insertion();
    }//GEN-LAST:event_tbbInsertActionPerformed

    private void tbbDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbbDeleteActionPerformed
        DeleteArtistAlbum();
    }//GEN-LAST:event_tbbDeleteActionPerformed

    private void  DeleteArtistAlbum() {
        //Διαγραφή άλμπουμ
        if ( LYRA.yesno("Θέλετε σίγουρα να διαγραφεί το άλμπουμ " +  album.getTitle().trim()) == 0 )
        {
            try {
                EntityTransaction et = null;
                et = LYRA.e.getTransaction();
                et.begin();
                
                Query queryDelete =  LYRA.e.createNativeQuery("DELETE FROM ADMIN1.Album a WHERE a.ALBUMID = " + album.getAlbumid().toString());
                queryDelete.executeUpdate();

                et.commit();
                parentForm.RefreshArtistAlbumTable();
                //Ενεργοποίηση της προηγούμενης φόρμας
                parentForm.EnableDisableForm(true);
                //Κλείσιμο φόρμας
                dispose();
            }
            catch (Exception e) {
                LYRA.MsgBox(e.getMessage(),"ΠΡΟΣΟΧΗ");
            }
            
        }
    }
    
    private boolean CloseForm() {
        if (!tbbExit.isEnabled()) return false;
        
        if (tbbExit.getText()=="Έξοδος")
        {
            LYRA.e.clear();
            parentForm.RefreshArtistAlbumTable();
            parentForm.setEnabled(true);
            return true;
        }
        else
        {
            if (bChanges)
            {
                if ( LYRA.yesno("Είστε σίγουροι ότι θέλετε να χαθούν οι αλλαγές; ") == 0 )
                {
                     LYRA.e.clear();
                     parentForm.RefreshArtistAlbumTable();
                     return true;
                } else {
                    FinisEdit();
                }
             } else {
                return true;
            }
        }
        return false;
    }
    
    private void tbbExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbbExitActionPerformed
        if (CloseForm()) {
            bFormClosing = true;
            parentForm.EnableDisableForm(true);
            dispose();
        }
    }//GEN-LAST:event_tbbExitActionPerformed

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        if (!bFormClosing) {
            if (CloseForm()) {
                bFormClosing = true;
                parentForm.EnableDisableForm(true);
                dispose();
            }
        } else {
            parentForm.EnableDisableForm(true);
            dispose();
        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void cmbAlbumTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbAlbumTypeActionPerformed
        if (bFormLoaded) setChanges(true);
        if ((cmbAlbumType.getSelectedItem()) != null) {
            if (!((Albumtype)(cmbAlbumType.getSelectedItem())).getName().toString().equals("LP")) {
                txtDiskNumber.setText("1");
                txtDiskNumber.setEnabled(false);
        } else {
                txtDiskNumber.setEnabled(true);
            }
            
        }
    }//GEN-LAST:event_cmbAlbumTypeActionPerformed

    private void txtDiskNumberKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDiskNumberKeyTyped
        if (bFormLoaded) setChanges(true);
    }//GEN-LAST:event_txtDiskNumberKeyTyped

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        try {
            ((SongTableModel)tblSongs.getModel()).addRow(new Object[] {null, "", 0, 0});
            ((SongTableModel)tblSongs.getModel()).fireTableDataChanged();
            setChanges(true);
        }  catch (Exception ex) {
            ex.printStackTrace(System.out);
            LYRA.MsgBox(ex.getMessage(), "Πρόβλημα");
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        if (tblSongs.getSelectedRowCount() > 0) {
            int TableRowToDelete = tblSongs.getSelectedRow();
            ((SongTableModel)tblSongs.getModel()).removeRow(TableRowToDelete);
            ((SongTableModel)tblSongs.getModel()).fireTableRowsDeleted(TableRowToDelete, TableRowToDelete);
            setChanges(true);
        } else {
            LYRA.MsgBox("Επιλέξτε πρώτα τραγούδι προς διαγραφή", "ΠΡΟΣΟΧΗ");        
        }
    }//GEN-LAST:event_btnRemoveActionPerformed

    private void cmbMusicProductionCompanyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbMusicProductionCompanyActionPerformed
        if (bFormLoaded) setChanges(true);
    }//GEN-LAST:event_cmbMusicProductionCompanyActionPerformed

    private void cmbArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbArtistActionPerformed
        if (bFormLoaded) setChanges(true);
    }//GEN-LAST:event_cmbArtistActionPerformed

    private void dtDateReleaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dtDateReleaseActionPerformed
        if (bFormLoaded) setChanges(true);
    }//GEN-LAST:event_dtDateReleaseActionPerformed

    private void UpdateArtistAlbum() {

        if (tbbModify.getText()=="Μεταβολή")
        {
            StartEdit();
        }
        else
        {
            if (isDataOK())
            {
                
                EntityTransaction et = null;
                
                try {

                    et = LYRA.e.getTransaction();
                    et.begin();
                    Collection<Song> newalbumCollection = album.getSongCollection();
                    if (newalbumCollection == null) {
                        newalbumCollection = new ArrayList<Song>();
                    }
                    
                    if (album.getAlbumid() == null) {
                        album.setArtisttype('A');
                         for (int curRow=0;curRow<curSongs.size();curRow++) {
                                Object[] row = (Object[]) curSongs.get(curRow);
                                Song new_sng = new Song();
                                new_sng.setAlbumid(album);
                                new_sng.setTitle((String)row[1]);
                                new_sng.setDuration((Integer)row[2]);
                                new_sng.setTracknr((Integer)row[3]);
                                LYRA.e.persist(new_sng);
                                newalbumCollection.add(new_sng);
                         }
                    }

                    if (album.getAlbumid()!= null) {
                       
                        if (curSongs.isEmpty() == false) {
                            
                            // removing songs
                            boolean found = false;
                            boolean removed = false;
                            while ((!found)||(removed))  {
                                removed = false;
                                Iterator sng_iter = newalbumCollection.iterator();
                                if (newalbumCollection.size() == 0) {
                                    break;
                                }
                                while (sng_iter.hasNext()) {
                                    Song iter = (Song) sng_iter.next();
                                    found = false;
                                    for (int curRow=0;curRow<curSongs.size();curRow++) {
                                        Object[] row = (Object[]) curSongs.get(curRow);
                                        if (row[0] != null) {
                                            if (iter.getSongid().equals((long)row[0])) {
                                                found = true;
                                                break;
                                            }
                                        }
                                    }

                                    if (!found) {
                                        
                                        Query queryDelete =  LYRA.e.createNativeQuery("DELETE FROM ADMIN1.Song sng WHERE sng.SongID = " + iter.getSongid().toString());
                                        queryDelete.executeUpdate();

                                        newalbumCollection.remove(iter);
                                        LYRA.e.remove(iter);
                                        removed = true;
                                        break;
                                    }
                                    
                                }
                                    
                            }
                            
                            for (int curRow=0;curRow<curSongs.size();curRow++) {
                                Object[] row = (Object[]) curSongs.get(curRow);
                                if (row[0] == null) {
                                    // adding new songs
                                    Song new_sng = new Song();
                                    new_sng.setAlbumid(album);
                                    new_sng.setDuration((Integer)row[2]);
                                    new_sng.setTitle((String)row[1]);
                                    new_sng.setTracknr((Integer)row[3]);
                                    LYRA.e.persist(new_sng);
                                    newalbumCollection.add(new_sng);
                                } else {
                                    // updating old ones
                                    Iterator sng_iter = newalbumCollection.iterator();
                                    while (sng_iter.hasNext()) {
                                        Song iter = (Song) sng_iter.next();
                                        if (iter.getSongid().equals((long)row[0])) {
                                            iter.setTitle((String)row[1]);
                                            iter.setDuration((Integer)row[2]);
                                            iter.setTracknr((Integer)row[3]);
                                            LYRA.e.persist(iter);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    album.setSongCollection(newalbumCollection);
                    LYRA.e.persist(album);

                    et.commit();
                    FinisEdit();
                    parentForm.RefreshArtistAlbumTable();
                    // Αφού αποθηκεύσαμε κλείνουμε και τη φόρμα
                    parentForm.EnableDisableForm(true);
                    this.dispose();
                } catch (Exception ex) {
                    LYRA.e.clear();
                    if (et.isActive()) et.rollback();
                    ex.printStackTrace(System.out);
                    LYRA.MsgBox(ex.getMessage(), "Πρόβλημα");
                }

            }
        }
    }
    
    private void setChanges( boolean modified )
    {
        if (modified)
        {
            tbbModify.setEnabled(true);
            tbbExit.setEnabled(true);            
        }
        //Ένδειξη ύπαρξης/μη ύπαρξης αλλαγών
        bChanges= modified;        
    }
    
    public final void Insertion() {

        //Δημιουργία νέου αντικειμένου artist της κλάσης Artist
        album = new Album();
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
        
        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${albumtypeid}"), cmbAlbumType, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);
        
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${title}"), txtTitle, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${disknumber}"), txtDiskNumber, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${releasedate}"), dtDateRelease, org.jdesktop.beansbinding.BeanProperty.create("date"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${artistid}"), cmbArtist, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, album, org.jdesktop.beansbinding.ELProperty.create("${musicproductioncompanyid}"), cmbMusicProductionCompany, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);
        
        bindingGroup.bind();
        
        setChanges(false);
        
        StartEdit();
        txtTitle.requestFocus();

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager LYRAPUEntityManager;
    private java.util.List<lyra.pojos.Albumtype> albumtypeList;
    private javax.persistence.Query albumtypeQuery;
    private java.util.List<lyra.pojos.Artist> artistList;
    private javax.persistence.Query artistQuery;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnRemove;
    private javax.swing.JComboBox cmbAlbumType;
    private javax.swing.JComboBox cmbArtist;
    private javax.swing.JComboBox cmbMusicProductionCompany;
    private org.jdesktop.swingx.JXDatePicker dtDateRelease;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane3;
    private java.util.List<lyra.pojos.Musicproductioncompany> musicproductioncompanyList;
    private javax.persistence.Query musicproductioncompanyQuery;
    private java.util.List<lyra.pojos.Song> songList;
    private javax.persistence.Query songQuery;
    private javax.swing.JToolBar tbarManage;
    private javax.swing.JButton tbbDelete;
    private javax.swing.JButton tbbExit;
    private javax.swing.JButton tbbInsert;
    private javax.swing.JButton tbbModify;
    private javax.swing.JTable tblSongs;
    private javax.swing.JTextField txtDiskNumber;
    private javax.swing.JTextField txtTitle;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
